package mysql

import (
	"gorm.io/gorm"
	"strconv"
)

type House struct {
	gorm.Model
	Name    string  `json:"name" gorm:"type:varchar(200);not null;comment:'房子名称'"`
	Price   float64 `json:"price" gorm:"type:float(10,2);not null;comment:'房子价格'"`
	Address string  `json:"address" gorm:"type:varchar(200);not null;comment:'房子地址'"`
	Hav     string  `json:"hav" gorm:"type:varchar(200);not null;comment:'房子面积'"`
	Img     string  `json:"img" gorm:"type:varchar(255);not null;comment:'图片'"`
}

func (h *House) Create() error {
	return DB.Create(&h).Error
}

func (h *House) Find(id int) error {
	return DB.Debug().Model(&House{}).Where("id=?", id).Limit(1).Find(&h).Error
}

func (h *House) List(keyWord string, page, pageSize int) (house []*House, err error) {
	query := DB.Debug().Model(&House{})
	if keyWord != "" {
		query = query.Where("name like ?", "%"+keyWord+"%")
	}
	err = query.Scopes(Paginate(page, pageSize)).Find(&house).Error
	return
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		page, _ = strconv.Atoi(strconv.Itoa(page))
		if page <= 0 {
			page = 1
		}

		pageSize, _ = strconv.Atoi(strconv.Itoa(pageSize))
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
